package com.blb.servlet.user;

import com.alibaba.fastjson.JSON;
import com.blb.dao.user.DeliverAddressDao;
import com.blb.pojo.UserAddress;
import com.blb.service.user.impl.DeliverAddressServiceImpl;
import com.blb.servlet.BaseServlet;
import com.blb.utils.ApplicationContextUtil;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@WebServlet(value = "/user/deliverAddress/*", loadOnStartup = 1)
public class deliverAddressServlet extends BaseServlet {

    private DeliverAddressServiceImpl dAService = (DeliverAddressServiceImpl) ApplicationContextUtil.getBean(DeliverAddressServiceImpl.class);

    // 回填数据
    public void deliverAddress(HttpServletRequest req, HttpServletResponse resp) {
        try {
            //获取地址信息
            List<UserAddress> userAddress = dAService.getUserAddress();
            req.setAttribute("userAddress",userAddress);
            forward("/user/view/index/deliverAddress");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void reviseDefault(HttpServletRequest req, HttpServletResponse resp){
        String id = req.getParameter("id");
        try {
            //修改默认状态
            dAService.reviseDefault(Integer.parseInt(id));
            forward("/user/deliverAddress/deliverAddress");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void addAddress(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        try {
        UserAddress address = getEntity(UserAddress.class);
        // 添加数据并设置默认值
        dAService.addAddress(address);
        forward("/user/deliverAddress/deliverAddress");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void ajaxGetAddress(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        try {
            String id = req.getParameter("id");
            System.out.println(id);
            // 根据传递过来的地址Id，查询数据
            UserAddress address = dAService.getAddressById(id);
            writeJson(JSON.toJSONString(address));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
